
package com.jf.cloud.service.sysmanager.remote.api;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jf.cloud.service.sysmanager.dao.*;
import com.jf.cloud.service.sysmanager.entity.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jf.cloud.service.sysmanager.common.base.OPaging;
import com.jf.cloud.service.sysmanager.common.db.Query;
import com.jf.cloud.service.sysmanager.common.taglib.Paging;
import com.jf.cloud.service.sysmanager.common.util.DateUtil;
import com.jf.cloud.service.sysmanager.common.util.JsonUtil;
import com.jf.cloud.service.sysmanager.common.util.StringUtil;
import com.jf.cloud.service.sysmanager.constant.MatchConstant;
import com.jf.cloud.service.sysmanager.constant.PubgConstant;
import com.jf.cloud.service.sysmanager.constant.UserConstant;
import com.jf.cloud.service.sysmanager.constant.UserMatchConstant;
import com.jf.cloud.service.sysmanager.handler.TokenHandler;
import com.jf.cloud.service.sysmanager.support.entity.Result;
import com.jf.cloud.service.sysmanager.support.handler.BaseDataBizHandler;
import com.jf.cloud.service.sysmanager.support.web.BaseController;

/**
 * 战队控制器
 * 
 * @author 代码机1.0 创建时间：2018-03-31
 */
@Controller
@RequestMapping("/appTeam")
public class AppPubgTeamController extends BaseController {

	/**
	 * 日志
	 */
	private static Log log = LogFactory.getLog(AppPubgTeamController.class);

	/**
	 * 用户-俱乐部关系服务
	 */
	@Resource
	private IPubgUserClubService pubgUserClubService;
	
	/**
	 * 战队服务
	 */
	@Resource
	private IPubgTeamService pubgTeamService;
	
	@Resource
	private IPubgUserService pubgUserService;

	@Resource
	private IPubgUserTeamService pubgUserTeamService;
	
	@Resource
	private IPubgUserMatchService pubgUserMatchService;
	
	@Resource
	private TokenHandler tokenHandler;
	
	@Resource
	private BaseDataBizHandler baseDataBizHandler;

	@Resource
	private IPubgOperateLogService pubgOperateLogService;
	
	@Resource
	private IPubgMsgLogService pubgMsgLogService;

	@Resource
	private IPubgMatchService pubgMatchService;

	@Resource
	private IPubgMatchRewardService pubgMatchRewardService;

	@Resource
	private IPubgClubService pubgClubService;

	@Resource
	private IPubgMatchSettlementService pubgMatchSettlementService;
	/**
	 * 战队列表数据
	 * 
	 * @author 朱建文 创建时间：2018-03-31
	 */
	@ResponseBody
	@RequestMapping("/myTeam")
	public Result<List<Map<String, Object>>> listPubgTeamData(OPaging<Map<String, Object>> page, HttpServletRequest request, HttpServletResponse response) {
		Result<List<Map<String, Object>>> result = new Result<List<Map<String, Object>>>();
		result.setCode(-1);
		result.setMessage("获取战队数据失败！");
		try {
			String token = getParamValueString(request, "token");
			String userId = tokenHandler.getCommUserInfoByToken(token);
            if (userId == null || userId.trim().length() == 0) {
                result.setCode(-2);
                result.setMessage("请重新登陆！");
                return result;
            }
            
			String userRole = getParamValueString(request, "userRole");
			if (StringUtil.isNull(userRole)) {
				result.setMessage("角色不合法！");
				return result;
			}

			// 每页数据条数
			int limit = getParamValueInteger(request, "limit", 50);
			page.setLimit(limit);

			// 第几页
			int offset = getParamValueInteger(request, "offset", -1);
			if (offset > 0) {
				page.setOffset((offset-1)*limit);
			}
			
			// 排序方式
			String order = getParamValueString(request, "order");
			if (StringUtil.isNotEmpty(order)) {
				page.setOrder(order);
			}
			
			// 排序字段
			String sort = getParamValueString(request, "sort"); 
			if (StringUtil.isNotEmpty(sort)) {
				page.setSort(sort);
			}
			
			page.getWm().put("USER_ID", userId);
			page.getWm().put("non_USER_ROLE", userRole);
			if(userRole.equals("20") || userRole.equals("30")){
				result.setCode(0);
				result.setMessage("未获取到数据！");
				return result;
			}

			List<Map<String, Object>> datalList = pubgTeamService.findPubgTeamListByRole(page);
			if (datalList == null || datalList.isEmpty()) {
				result.setCode(0);
				result.setMessage("未获取到数据！");
				return result;
			}
			result.setData(datalList);
			result.setCode(0);
			result.setMessage("获取战队列表数据成功！");
		} catch (Exception e) {
			log.error("获取战队列表数据出错！", e);
		}
		return result;
	}

	/**
	 * 获取战队详情
	 * 
	 * @author 朱建文 创建时间：2018年4月2日 上午10:18:22
	 */
	@ResponseBody
	@RequestMapping("/pubgTeamDetail")
	public Result<Map<String, Object>> pubgTeamDetail(String token, String userRole, Long rowId, HttpServletRequest request, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		Result<Map<String, Object>> result = new Result<Map<String, Object>>();
		result.setCode(-1);
		result.setMessage("获取战队详情失败！");
		try {
			String userId = tokenHandler.getCommUserInfoByToken(token);
			if (userId == null || userId.trim().length() == 0) {
			    result.setCode(-2);
			    result.setMessage("请重新登陆！");
			    return result;
			}
			if (StringUtil.isNull(userRole)) {
				result.setMessage("用户角色为空！");
				return result;
			}
			if (StringUtil.isNull(rowId + "") && !UserConstant.USER_ROLE_20.getId().equals(Integer.valueOf(userRole))) {
				result.setMessage("id不合法！");
				return result;
			}
			
			Map<String, Object> dataMap = this.pubgTeamService.findPubgTeamDetail(Long.valueOf(userId), userRole, rowId);
			result.setData(dataMap);
			result.setCode(0);
			result.setMessage("获取战队详情成功！");
			log.info(result);
		} catch (Exception e) {
			log.error("获取战队详情失败！", e);
		}
		return result;
	}

	/**
	 * 添加/修改战队
	 * 
	 * @author 朱建文 创建时间：2018年4月3日 下午2:01:17
	 */
	@ResponseBody
	@RequestMapping("/addPubgTeam")
	public Result<String> addPubgTeam(String token, PubgTeam pubgTeam, HttpServletRequest request, HttpServletResponse response){
		response.setHeader("Access-Control-Allow-Origin", "*");
		Result<String> result = new Result<String>();
		result.setCode(-1);
		result.setMessage("获取战队详情失败！");
		try {
			String userId = tokenHandler.getCommUserInfoByToken(token);
			if (userId == null || userId.trim().length() == 0) {
				result.setMessage("请重新登陆！");
			    return result;
			}
			if (pubgTeam == null) {
				return result;
			}
			
			PubgUser pubgUser = this.pubgUserService.findByPK(Long.valueOf(userId));
			if (!pubgUser.getUserRole().equals(UserConstant.USER_ROLE_30.getId())) {
				result.setMessage("您当前无权限添加战队");
				return result;
			}
			
			// 当前操作人的 俱乐部关系
			Query query = new Query();
			query.put("_LIKE$MINISTER_ID", "," + userId + ",");
			PubgClub pubgClub = pubgClubService.find(query);
			if (pubgClub == null) {
				result.setMessage("您当前无权限添加战队");
				return result;
			}
			
			// 校验参数
			result = checkParam(pubgTeam, result);
			if (1 != result.getCode()) {
				result.setCode(-1);
				return result;
			}
			pubgTeam.setOptId(pubgUser.getRowId());
			pubgTeam.setOptAccount(pubgUser.getUserAccount());
			pubgTeam.setOptTime(DateUtil.getCurrentDateTime());
			pubgTeam.setClubId(pubgClub.getRowId());
			pubgTeam.setClubName(pubgClub.getClubName());
			pubgTeamService.addPubgTeam(pubgTeam);
			result.setCode(0);
			result.setMessage("添加/修改战队成功！");
			
			// 插入添加/修改战队
			if (pubgTeam.getRowId() == null) {
				pubgOperateLogService.insertUserOperateLog(pubgUser.getRowId(), null, "添加战队【" + pubgTeam.getTeamName() + "】" + JsonUtil.toJSON(pubgTeam));
			} else {
				pubgOperateLogService.insertUserOperateLog(pubgUser.getRowId(), null, "修改战队【" + pubgTeam.getTeamName() + "】" + JsonUtil.toJSON(pubgTeam));
			}
		} catch (Exception e) {
			log.error("添加/修改战队出错！", e);
		}
		return result;
	}
	
	/**
	 * 添加战队时 校验参数是否完整
	 * 
	 * @author 朱建文 创建时间：2018年4月3日 下午2:05:19
	 */
	private Result<String> checkParam(PubgTeam pubgTeam, Result<String> result){
		result.setCode(-1);
		try {
			if (StringUtil.isNull(pubgTeam.getTeamNo())) {
				result.setMessage("战队靓号为空！");
				return result;
			}
			// 验证战队靓号是否存在  战队
			boolean isExist = this.pubgTeamService.checkTeamNoIsExist(pubgTeam.getRowId(), pubgTeam.getTeamNo());
			if (isExist) {
				result.setMessage("战队靓号已存在！");
				return result;
			}
			if (StringUtil.isNull(pubgTeam.getTeamName())) {
				result.setMessage("战队名称为空！");
				return result;
			}
			if (StringUtil.isNull(pubgTeam.getPlaceProvince())
					|| StringUtil.isNull(pubgTeam.getPlaceCity())
					|| StringUtil.isNull(pubgTeam.getPlaceDistrict())) {
				result.setMessage("省市区为空！");
				return result;
			}
			if (StringUtil.isNull(pubgTeam.getTeamAddress())) {
				result.setMessage("详细地址为空！");
				return result;
			}
			if (StringUtil.isNull(pubgTeam.getTeamPhoto())) {
				result.setMessage("战队图片为空！");
				return result;
			}
			if (StringUtil.isNull(pubgTeam.getTeamIntro())) {
				result.setMessage("战队简介为空！");
				return result;
			}
			if (StringUtil.isNull(pubgTeam.getInviteCode())) {
				result.setMessage("邀请码为空！");
				return result;
			}
			if (pubgTeam.getSettlementRatio() == null) {
				result.setMessage("结算比例不能为空！");
				return result;
			}
			if (pubgTeam.getSettlementRatio() < 0 || pubgTeam.getSettlementRatio() >= 1) {
				result.setMessage("结算比例取值范围（0-1）之间！");
				return result;
			}
			// 验证邀请码是否存在  俱乐部
			isExist = this.baseDataBizHandler.checkClubInvitelCodeIsExist(null, pubgTeam.getInviteCode());
			if (isExist) {
				result.setMessage("邀请码已存在！");
				return result;
			}
			isExist = this.baseDataBizHandler.checkTeamInvitelCodeIsExist(pubgTeam.getRowId(), pubgTeam.getInviteCode());
			if (isExist) {
				result.setMessage("邀请码已存在！");
				return result;
			}
			
			if (StringUtil.isNull(pubgTeam.getCaptainAccount())) {
				result.setMessage("队长为空！");
				return result;
			}
			
			// 验证队长状态、获取队长ID
			result = baseDataBizHandler.bulidUserIdByAccount(result, pubgTeam.getCaptainAccount(), UserConstant.USER_ROLE_20.getId(), pubgTeam.getRowId());
			if (1 != result.getCode()) {
				return result;
			}
			pubgTeam.setCaptainId(result.getData());
			
			if (!StringUtil.isDouble(pubgTeam.getSettlementRatio() + "")
					&& !StringUtil.isInteger(pubgTeam.getSettlementRatio() + "")) {
				result.setMessage("结算比例为空！");
				return result;
			}
			result.setCode(1);
		} catch (Exception e) {
			log.error("添加战队时 校验参数是否完整出错！", e);
		}
		return result;
	}

	/**
	 * 审核队员是否加入战队、（加入/拒绝）
	 * 
	 * @author 朱建文 创建时间：2018年4月4日 上午10:49:05
	 */
	@ResponseBody
	@RequestMapping("/auditMemberIsJoin")
	public Result<String> auditMemberIsJoin(String token, Long userId, HttpServletRequest request){
		Result<String> result = new Result<String>();
		result.setCode(-1);
		result.setMessage("审核队员失败！");
		try {
		
			// 验证token
			String optId = tokenHandler.getCommUserInfoByToken(token);
			if (optId == null || optId.trim().length() == 0) {
				result.setCode(-2);
				result.setMessage("请重新登陆！");
			    return result;
			}
			
			// 操作人是否是队长
			PubgUser pubgUser = this.pubgUserService.findByPK(Long.valueOf(optId));
			if (!pubgUser.getUserRole().equals(UserConstant.USER_ROLE_20.getId())) {
				result.setMessage("您当前无权移除战队");
				return result;
			}

			// 查询战队信息
			Query query = new Query();
			query.put("_LIKE$CAPTAIN_ID", "," + optId + ",");
			PubgTeam pubgTeam = this.pubgTeamService.find(query);
			if (pubgTeam == null) {
				result.setMessage("您当前无权移除战队");
				return result;
			}

			// 验证队员的状态
			Integer relationState = getParamValueInteger(request, "relationState", 0);
			if (relationState == null 
					|| (!relationState.equals(PubgConstant.USER_TEAM_RELATION_STATE_2)
					&& !relationState.equals(PubgConstant.USER_TEAM_RELATION_STATE_3))) {
				result.setMessage("状态有误！");
				return result;
			}
			
			// 队员是否该战队成员
			query = new Query();
			query.put("USER_ID", userId);
			query.put("TEAM_ID", pubgTeam.getRowId());
			query.put("RELATION_STATE", "1");
			List<PubgUserTeam> tempList = this.pubgUserTeamService.findList(query);
			if (tempList == null || tempList.isEmpty()) {
				result.setMessage("当前队员未申请您的战队或申请已被处理！");
				return result;
			}
			if (tempList.size() > 1) {
				result.setMessage("申请信息存在多个，请联系管理员！");
				return result;
			}
			
			PubgUserTeam pubgUserTeam = tempList.get(0);
			if (pubgUserTeam == null) {
				result.setMessage("当前队员未申请您的战队");
				return result;
			}
			
			// 拒绝，直接更新队员-战队，俱乐部关系表
			String relationDes = "拒绝队员（" + pubgUserTeam.getUserAccount() + "）加入战队：" + pubgUserTeam.getUserAccount();
			if (relationState.equals(PubgConstant.USER_TEAM_RELATION_STATE_3)) {
				if (pubgUserTeam.getRelationState().equals(PubgConstant.USER_TEAM_RELATION_STATE_3)) {
					result.setCode(0);
					result.setMessage("当前队员已拒绝");
					return result;
				}
				
			// 同意，更新队员-战队，俱乐部关系表，并更新战队、俱乐部下总人数
			} else {
				relationDes = "同意队员（" + pubgUserTeam.getUserAccount() + "）加入战队：" + pubgUserTeam.getUserAccount();
				if (pubgUserTeam.getRelationState().equals(PubgConstant.USER_TEAM_RELATION_STATE_2)) {
					result.setCode(0);
					result.setMessage("当前队员已审核通过");
					return result;
				}
			}
			this.pubgTeamService.updateMemberRelationState(pubgUserTeam, relationState);
			result.setCode(0);
			result.setMessage("审核队员成功！");
			
			
			// 记录操作日志
			pubgOperateLogService.insertUserOperateLog(pubgUser.getRowId(), null, relationDes + "-" + pubgTeam.getTeamName());
			
//			// 插入用户消息
//			if (relationState.equals(PubgConstant.USER_TEAM_RELATION_STATE_3)) {
//				String msgContent = "战队【" + pubgUserTeam.getUserAccount() + "】拒绝您加入";
//				pubgMsgLogService.insertPbugMsgLog(Long.valueOf(userId), 10L, msgContent);
//			}
		} catch (Exception e) {
			log.error("审核队员是否加入战队出错！", e);
		}
		return result;
	}
	
	/**
	 * 给队员加减款
	 * 
	 * @author 朱建文 创建时间：2018年4月4日 下午5:13:11
	 */
	@ResponseBody
	@RequestMapping("/updateTeamMemberBalance")
	public Result<String> updateTeamMemberBalance(Long memberId, Double optMoney, HttpServletRequest request){
		Result<String> result = new Result<String>();
		result.setCode(-1);
		result.setMessage("更新队员余额失败！");
		
		try {
			// 验证token
			String token = getParamValueString(request, "token");
			String optId = tokenHandler.getCommUserInfoByToken(token);
			if (optId == null || optId.trim().length() == 0) {
				result.setCode(-2);
				result.setMessage("请重新登陆！");
			    return result;
			}
			
			// 验证 操作方式   1 加款   2 减款
			int optType = getParamValueInteger(request, "optType", -1);
			if (optType < 0) {
				result.setMessage("操作方式为空！");
				return result;
			}
			if (optMoney == null || optMoney < 0) {
				result.setMessage("操作金额必须大于0！");
				return result;
			}
			
			// 用户是否存在
			PubgUser pubgUser = this.pubgUserService.findByPK(memberId);
			if (pubgUser == null) {
				result.setMessage("用户不存在！");
				return result;
			}
			
			// 操作者是否是队长
			Query query = new Query();
			query.put("_LIKE$CAPTAIN_ID", "," + optId + ",");
			PubgTeam pubgTeam = this.pubgTeamService.find(query);
			if (pubgTeam == null) {
				result.setMessage("您当前还不是队长！");
				return result;
			}
			
			// 加，需要验证战队下的余额
			if (1 == optType && optMoney > pubgTeam.getTeamBalance()) {
				result.setMessage("操作金额不能大于俱乐部的余额！");
				return result;
			}
			
			// 查询用户-战队
			query = new Query();
			query.put("USER_ID", pubgUser.getRowId());
			query.put("TEAM_ID", pubgTeam.getRowId());
			query.put("RELATION_STATE", PubgConstant.USER_TEAM_RELATION_STATE_2);
			PubgUserTeam pubgUserTeamTemp = this.pubgUserTeamService.find(query);
			
			// 如果是减，需要验证当前队员余额
			if (2 == optType && optMoney > pubgUserTeamTemp.getUserTeamBalance()) {
				result.setMessage("操作金额不能大于战队的余额！");
				return result;
			}
			
			// 查询用户-俱乐部
			query = new Query();
			query.put("USER_ID", pubgUser.getRowId());
			query.put("CLUB_ID", pubgUserTeamTemp.getClubId());
			List<PubgUserClub> pubgUserClubList = this.pubgUserClubService.findList(query);
			
			// 更新队员余额、充值总额
			PubgUserTeam pubgUserTeam = new PubgUserTeam();
			pubgUserTeam.setClubId(pubgTeam.getClubId());
			pubgUserTeam.setClubName(pubgTeam.getClubName());
			pubgUserTeam.setTeamId(pubgTeam.getRowId());
			pubgUserTeam.setTeamName(pubgTeam.getTeamName());
			pubgUserTeam.setUserId(pubgUser.getRowId());
			pubgUserTeam.setUserAccount(pubgUser.getUserAccount());
			pubgUserTeam.setUserTeamBalance(pubgUserTeamTemp.getUserTeamBalance());
			pubgUserTeam.setWinSum(pubgUser.getBalance()); // 临时借用  存队员的总余额
			pubgUserTeam.setRechargeSum(pubgUserClubList.get(0).getUserClubBalance());  // 临时借用  存队员在该俱乐部下的余额
			this.pubgTeamService.updateTeamMemberBalance(pubgTeam, pubgUserTeam, optType, optMoney);
			
			// 插入操作记录
			PubgUser optUser = this.pubgUserService.findByPK(Long.valueOf(optId));
			String relationDes = optUser.getUserAccount() + "对队员【" + pubgTeam.getTeamName() + "】加鸡蛋" + optMoney;
			if (2 == optType) {
				relationDes = optUser.getUserAccount() + "对队员【" + pubgTeam.getTeamName() + "】减鸡蛋：" + optMoney;
			}
			pubgOperateLogService.insertUserOperateLog(pubgUser.getRowId(), null, relationDes);
			result.setCode(0);
			result.setMessage("更新队员余额成功！");
		} catch (Exception e) {
			log.error("更新队员余额出错！", e);
		}
		return result;
	}
	
	/**
	 * 移除队员
	 * 
	 * @author 朱建文 创建时间：2018年4月2日 下午1:13:11
	 */
	@ResponseBody
	@RequestMapping("/removeTeamMember")
	public Result<String> removeUser(String token, Long userId, HttpServletRequest request){
		Result<String> result = new Result<String>();
		result.setCode(-1);
		result.setMessage("移除队员失败！");
		try {
			String optId = tokenHandler.getCommUserInfoByToken(token);
			if (optId == null || optId.trim().length() == 0) {
				result.setCode(-2);
				result.setMessage("请重新登陆！");
			    return result;
			}
			
			// 验证战队 队长信息
			PubgUser pubgUser = this.pubgUserService.findByPK(Long.valueOf(optId));
			if (UserConstant.USER_ROLE_20.getId().intValue() != pubgUser.getUserRole()) {
				result.setMessage("您当前无权移除战队");
				return result;
			}
			
			// 查询战队信息
			Query query = new Query();
			query.put("_LIKE$CAPTAIN_ID", "," + optId + ",");
			PubgTeam pubgTeam = this.pubgTeamService.find(query);
			if (pubgTeam == null) {
				result.setMessage("您当前无权移除战队");
				return result;
			}
			
			// 验证当前队员是否该战队
			query = new Query();
			query.put("USER_ID", userId);
			query.put("TEAM_ID", pubgTeam.getRowId());
			PubgUserTeam pubgUserTeam = this.pubgUserTeamService.find(query);
			if (pubgUserTeam == null) {
				result.setMessage("当前队员不属于您的战队");
				return result;
			}
			
			// 验证队员的状态
			if (pubgUserTeam.getRelationState().equals(PubgConstant.USER_TEAM_RELATION_STATE_4)) {
				result.setCode(0);
				result.setMessage("当前队员已被移除");
				return result;
			}
			
			// 移除队员 并更新战队的总队员数
			this.pubgTeamService.removeUser(pubgTeam.getClubId(), pubgTeam.getRowId(), Long.valueOf(userId));
			result.setCode(0);
			result.setMessage("移除队员成功！");
			
			// 记录操作日志
			pubgOperateLogService.insertUserOperateLog(pubgUser.getRowId(), null, "移除队员：" + pubgUserTeam.getUserAccount());
//			
//			// 给队员记录消息
//			pubgMsgLogService.insertPbugMsgLog(Long.valueOf(userId), 10L, "您已被移除【" + pubgUserTeam.getTeamName() + "】战队！");
		} catch (Exception e) {
			log.error("移除队员出错！", e);
		}
		return result;
	}

	/**
	 * 队员是否加入赛事的审核列表
	 * 
	 * @author 朱建文 创建时间：2018年4月11日 下午4:02:32
	 */
	@ResponseBody
	@RequestMapping("/auditMemberJoinMacthList")
	public Result<Map<String, Object>> auditMemberJoinMacthList(Long matchId, String userName, HttpServletRequest request){
		Result<Map<String, Object>> result = new Result<Map<String, Object>>();
		result.setCode(-1);
		result.setMessage("获取赛事审核列表失败！");
		try {
		
			// 验证token
			String token = getParamValueString(request, "token");
			String optId = tokenHandler.getCommUserInfoByToken(token);
			if (optId == null || optId.trim().length() == 0) {
				result.setCode(-2);
				result.setMessage("请重新登陆！");
			    return result;
			}

			// 验证操作者是否是队长
			Query query = new Query();
			query.put("_LIKE$CAPTAIN_ID", "," + optId + ",");
			PubgTeam pubgTeam = this.pubgTeamService.find(query);
			if (pubgTeam == null) {
				result.setMessage("您当前无权操作！");
				return result;
			}
			
			Map<String, Object> dataMap = this.pubgTeamService.getAuditMemberJoinMacthList(matchId, pubgTeam.getRowId(), userName);
			result.setCode(0);
			result.setData(dataMap);
			result.setMessage("获取审核列表成功");
		} catch (Exception e) {
			log.error("队员是否加入赛事的审核列表出错！", e);
		}
		return result;
	}

	/**
	 * 审核队员是否加入比赛、（同意/拒绝）
	 * 
	 * @author 朱建文 创建时间：2018年4月8日 上午10:49:05
	 */
	@ResponseBody
	@RequestMapping("/auditMemberIsJoinMacth")
	public Result<String> auditMemberIsJoinMacth(Long userId, Long matchId, HttpServletRequest request){
		Result<String> result = new Result<String>();
		result.setCode(-1);
		result.setMessage("审核队员失败！");
		try {
		
			// 验证token
			String token = getParamValueString(request, "token");
			String optId = tokenHandler.getCommUserInfoByToken(token);
			if (optId == null || optId.trim().length() == 0) {
				result.setCode(-2);
				result.setMessage("请重新登陆！");
			    return result;
			}
			
			// 验证操作者是否是队长
			Query query = new Query();
			query.put("_LIKE$CAPTAIN_ID", "," + optId + ",");
			PubgTeam pubgTeam = this.pubgTeamService.find(query);
			if (pubgTeam == null) {
				result.setMessage("您当前无权操作！");
				return result;
			}
			
			// 审核状态   1 同意		2 拒绝
			int auditState = getParamValueInteger(request, "auditState", -1);
			if (auditState != 1 && auditState != 2) {
				result.setMessage("状态错误！");
				return result;
			}
			
			// 验证队员是否存在、是否是你的战队
			PubgUser pubgUser = this.pubgUserService.findByPK(Long.valueOf(userId));
			if (pubgUser == null) {
				result.setMessage("该队员不存在");
				return result;
			}
			query = new Query();
			query.put("USER_ID", userId);
			query.put("TEAM_ID", pubgTeam.getRowId());
			query.put("RELATION_STATE", PubgConstant.USER_TEAM_RELATION_STATE_2);
			PubgUserTeam pubgUserTeam = this.pubgUserTeamService.find(query);
			if (pubgUserTeam == null) {
				result.setMessage("该队员不在你的战队！");
				return result;
			}
			
			PubgMatch pubgMatch = this.pubgMatchService.findByPK(matchId);
			if (pubgMatch == null) {
				result.setMessage("赛事不存在！");
				return result;
			}
			
			// 验证用户是否已经申请 战队的比赛
			query = new Query();
			query.put("USER_ID", userId);
			query.put("TEAM_ID", pubgTeam.getRowId());
			query.put("MATCH_ID", matchId);
			query.put("USER_STATE", UserMatchConstant.USER_MATCH_10.getId());
			PubgUserMatch pubgUserMatch = this.pubgUserMatchService.find(query);
			if (pubgUserMatch == null) {
				result.setMessage("该队员未申请你的赛事！");
				return result;
			}
			pubgUserMatch.setMatchPeopleNum(pubgMatch.getMatchPeopleNum());
			
			// 同意 更新用户状态、参赛总数；拒绝 回退资金，生成财务流水
			this.pubgTeamService.auditMemberIsJoinMacth(pubgUserMatch, auditState, pubgUserTeam.getUserTeamBalance(), pubgUser.getBalance());
			result.setCode(0);
			result.setMessage("操作成功！");
			
			// 记录操作日志
			String relationDes = "同意";
			if (auditState == 2) {
				relationDes = "拒绝";
				
				// 给队员记录消息
				pubgMsgLogService.insertPbugMsgLog(Long.valueOf(userId), 10L, "报名被拒通知", "赛事资格审核失败，详情联系队长！");
			}
			relationDes += "【" + pubgUser.getUserAccount() + "】加入【" + pubgUserMatch.getMatchName() + "】比赛";
			pubgOperateLogService.insertUserOperateLog(Long.valueOf(optId), null, relationDes);
		} catch (Exception e) {
			log.error("审核队员是否加入战队出错！", e);
		}
		return result;
	}
	
	/**
	 * 获取战队字典列表
	 * 
	 * @author 朱建文 创建时间：2018年4月2日 上午11:18:12
	 */
	@ResponseBody
	@RequestMapping("/pubgTeamDictList")
	public Result<List<Map<String, Object>>> pubgTeamDictList(String token, HttpServletRequest request) {
		Result<List<Map<String, Object>>> result = new Result<List<Map<String, Object>>>();
		result.setCode(-1);
		result.setMessage("获取战队字典列表数据失败！");
		try {
			String userId = tokenHandler.getCommUserInfoByToken(token);
			if (userId == null || userId.trim().length() == 0) {
			    return result;
			}
			
			PubgUser pubgUser = this.pubgUserService.findByPK(Long.valueOf(userId));
			List<Map<String, Object>> data = this.baseDataBizHandler.getPubgTeamDictList(pubgUser);
			result.setCode(0);
			result.setData(data);
			result.setMessage("获取战队字典列表数据成功！");
		} catch (NumberFormatException e) {
			log.error("获取战队字典列表出错！", e);
		}
		return result;
	}

	/**
	 * 战队大厅列表
	 *
	 * @author 高冬冬 创建时间：2018-04-04
	 */
	@ResponseBody
	@RequestMapping("/pubgTeamList")
	public Result<List<PubgTeam>> pubgTeamList(OPaging<PubgTeam> page, HttpServletRequest request, HttpServletResponse response) {
		Result<List<PubgTeam>> result = new Result<List<PubgTeam>>();
		result.setCode(-1);
		result.setMessage("获取战队大厅列表失败！");
		try {
			String token = getParamValueString(request, "token");
			String userId = tokenHandler.getCommUserInfoByToken(token);
			if (userId == null || userId.trim().length() == 0) {
				result.setCode(-2);
				result.setMessage("请重新登陆！");
				return result;
			}

			// 每页数据条数
			int limit = getParamValueInteger(request, "limit", 50);
			page.setLimit(limit);

			// 第几页
			int offset = getParamValueInteger(request, "offset", -1);
			if (offset > 0) {
				page.setOffset((offset-1)*limit);
			}

			// 排序方式
			String order = getParamValueString(request, "order");
			if (StringUtil.isNotEmpty(order)) {
				page.setOrder(order);
			}

			// 排序字段
			String sort = getParamValueString(request, "sort");
			if (StringUtil.isNotEmpty(sort)) {
				page.setSort(sort);
			}

			// 战队名称
			String teamName = getParamValueString(request, "teamName");
			if (StringUtil.isNotEmpty(teamName)) {
				page.getWm().put("NAME_LIKE&TEAM_NAME",teamName);
				page.getWm().put("NAME_LIKE&TEAM_NO",teamName);
			}

			PubgUser pubgUser = pubgUserService.findByPK(Long.parseLong(userId));
			if (pubgUser.getUserRole() != UserConstant.USER_ROLE_10.getId().intValue()) {
				result.setCode(0);
				result.setData(new ArrayList<PubgTeam>());
				result.setMessage("获取战队大厅列表数据成功！");
			return result;
            }
            //返回的数据集合
			Map<String,String> columns = new HashMap<String,String>();
			columns.put("ROW_ID", "rowId");
			columns.put("TEAM_NAME", "teamName");
			columns.put("TEAM_PHOTO", "teamPhoto");
			columns.put("MEMBER_NUM", "memberNum");
			columns.put("PLACE_PROVINCE", "placeProvince");
			columns.put("PLACE_CITY", "placeCity");
			columns.put("PLACE_DISTRICT", "placeDistrict");
			columns.put("TEAM_ADDRESS", "teamAddress");
			columns.put("PLACE_LONGITUDE", "placeLongitude");
			columns.put("PLACE_LATITUDE", "placeLatitude");
            Paging<PubgTeam> pageTemp = pubgTeamService.findPage(columns,page);
            if (pageTemp != null && pageTemp.getDataList().size() > 0) {
                for (PubgTeam pubgTeam:pageTemp.getDataList()) {
                    //查询用户与战队的关系
					columns = new HashMap<String,String>();
					columns.put("RELATION_STATE", "relationState");
                    Query query = new Query();
                    query.put("USER_ID",pubgUser.getRowId());
                    query.put("TEAM_ID",pubgTeam.getRowId());
                    query.orderBy("APPLY_TIME=DESC");
                    List<PubgUserTeam> pubgUserTeamList = pubgUserTeamService.findList(columns,query);
                    if (pubgUserTeamList != null && !pubgUserTeamList.isEmpty()) {
						pubgTeam.setRelationState(pubgUserTeamList.get(0).getRelationState());
                    }
                    
                    //查询战队参与的未结束未取消赛事
					columns = new HashMap<String,String>();
					columns.put("ROW_ID", "rowId");
                    query = new Query();
                    query.put("_LIKE$MATCH_TEAM_ID", "," + pubgTeam.getRowId()+",");
                    query.put("_NOT_IN$MATCH_STATE","'70','80'");
                    List<PubgMatch> matchList = pubgMatchService.findList(columns,query);
                    if (matchList != null && matchList.size() > 0) {
						pubgTeam.setNotEndMatchCount(matchList.size());
                    } else {
						pubgTeam.setNotEndMatchCount(0);
                    }
                }
            }
			result.setData(pageTemp.getDataList());
			result.setCode(0);
			result.setMessage("获取战队大厅列表数据成功！");
		} catch (Exception e) {
			log.error("获取战队大厅列表数据出错！", e);
		}
		return result;
	}


	/**
	 * 确认名次
	 * @param token
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/confirmRanking")
	public Result<PubgMatch> confirmRanking(String token, HttpServletRequest request){
		Result<PubgMatch> result = new Result<PubgMatch>();
		result.setCode(-1);
		result.setMessage("确认名次失败！");
		try{

            String cuurrentUserId = tokenHandler.getCommUserInfoByToken(token);
            if (cuurrentUserId == null || cuurrentUserId.trim().length() == 0) {
               	result.setCode(-2);
				result.setMessage("请重新登陆！");
				return result;
            }

			// 赛事
			String matchId = getParamValueString(request,"matchId");
			if (StringUtil.isEmpty(matchId)) {
				return new Result.ResultBuiler().failed("赛事id缺少！");
			}

			// 战队用户
			String userId = getParamValueString(request,"userId");
			if (StringUtil.isEmpty(userId)) {
				return new Result.ResultBuiler().failed("用户id为空！");
			}

			// 比赛结果
			String matchResult = getStringValue(request,"matchResult");
			if (StringUtil.isEmpty(matchResult) || !StringUtil.isInteger(matchResult)) {
				return new Result.ResultBuiler().failed("比赛结果为空！");
			}

			// 俱乐部id和战队id
			Map<String, Object> userInfo = this.pubgUserMatchService.getUserInfo(matchId);
			if (StringUtil.isEmpty(userInfo)) {
				return new Result.ResultBuiler().failed("俱乐部战队id不存在！");
			}

			// 查询赛事
			PubgMatch pubgMatch = this.pubgMatchService.findByPK(Long.valueOf(matchId));
			if (pubgMatch == null) {
				return new Result.ResultBuiler().failed("赛事不存在！");
			}
			if (!MatchConstant.MATCH_STATE_60.getId().toString().equals(pubgMatch.getMatchState())) {
				return new Result.ResultBuiler().failed("赛事状态错误！");
			}

			//查询赛事奖励设置
			Map<String,String> columns = new HashMap<String,String>();
			columns.put("ROW_ID", "rowId");
			Query query = new Query();
			query.put("MATCH_ID", matchId);
			query.put("RANKING", Integer.valueOf(matchResult));
			List<PubgMatchReward> matchRewardList = pubgMatchRewardService.findList(columns, query);
			//验证奖励设置是否有此名次
			if (matchRewardList == null || matchRewardList.size() == 0) {
				result.setMessage("奖励设置中不存在此名次，无法确认！");
				return result;
			}
			//验证输入的名次是否超出数量限制
			columns = new HashMap<String,String>();
			columns.put("ROW_ID", "rowId");
			query = new Query();
			query.put("MATCH_ID",matchId);
			query.put("CLUB_ID",userInfo.get("clubId"));
			query.put("MATCH_RESULT",Integer.valueOf(matchResult));
			query.put("USER_STATE", UserMatchConstant.USER_MATCH_20.getId());
			List<PubgUserMatch> pubgUserMatchList = this.pubgUserMatchService.findList(columns, query);
			if (pubgMatch.getMatchTypeId().intValue() == MatchConstant.MATCH_TYPE_2.getId().intValue()) {
				if (pubgUserMatchList != null && pubgUserMatchList.size() == 1) {
					result.setMessage("单排比赛只能设置一个第"+matchResult+"名！");
					return result;
				}
			} else if (pubgMatch.getMatchTypeId().intValue() == MatchConstant.MATCH_TYPE_3.getId().intValue()) {
				if (pubgUserMatchList != null && pubgUserMatchList.size() == 2) {
					result.setMessage("双排比赛只能设置两个第"+matchResult+"名！");
					return result;
				}
			}if (pubgMatch.getMatchTypeId().intValue() == MatchConstant.MATCH_TYPE_4.getId().intValue()) {
				if (pubgUserMatchList != null && pubgUserMatchList.size() == 4) {
					result.setMessage("四排比赛只能设置四个第"+matchResult+"名！");
					return result;
				}
			}if (pubgMatch.getMatchTypeId().intValue() == MatchConstant.MATCH_TYPE_5.getId().intValue()) {
				if (pubgUserMatchList != null && pubgUserMatchList.size() == 8) {
					result.setMessage("八排比赛只能设置八个第"+matchResult+"名！");
					return result;
				}
			}
			query = new Query();
			query.put("MATCH_ID",matchId);
			query.put("CLUB_ID",userInfo.get("clubId"));
			query.put("TEAM_ID",userInfo.get("teamId"));
			query.put("USER_ID",userId);
			query.put("USER_STATE", UserMatchConstant.USER_MATCH_20.getId());
			PubgUserMatch pubgUserMatch = this.pubgUserMatchService.find(query);
			if (StringUtil.isEmpty(pubgUserMatch)) {
				return new Result.ResultBuiler().failed("用户报名信息不存在！");
			}

			// 名次
			pubgUserMatch.setRowId(pubgUserMatch.getRowId());
			pubgUserMatch.setResultSubmitTime(DateUtil.getCurrentDateTime());
			pubgUserMatch.setMatchResult(Integer.valueOf(matchResult));

			PubgMatchSettlement pubgMatchSettlement = new PubgMatchSettlement();

			// 赛事
			pubgMatchSettlement.setMatchId(pubgUserMatch.getMatchId());
			pubgMatchSettlement.setMatchName(pubgUserMatch.getMatchName());
            pubgMatchSettlement.setMatchType(pubgMatch.getMatchTypeId());
            pubgMatchSettlement.setMatchTypeName(pubgMatch.getMatchType());

			// 俱乐部
			pubgMatchSettlement.setClubId(pubgUserMatch.getClubId());
			pubgMatchSettlement.setClubName(pubgUserMatch.getClubName());

			// 战队
			pubgMatchSettlement.setTeamId(pubgUserMatch.getTeamId());
			pubgMatchSettlement.setTeamName(pubgUserMatch.getTeamName());

			// 队员
			pubgMatchSettlement.setUserId(pubgUserMatch.getUserId());
			pubgMatchSettlement.setUserAccount(pubgUserMatch.getUserAccount());

			// 报名时间 获得名次
			pubgMatchSettlement.setApplyTime(pubgUserMatch.getApplyTime());
			pubgMatchSettlement.setApplyFee(pubgUserMatch.getApplyFee());
			pubgMatchSettlement.setMatchResult(matchResult);
			pubgMatchSettlement.setObtainRank(matchResult);

			// 战绩提交人
			PubgUser pubgUserSubmit = this.pubgUserService.findByPK(Long.valueOf(cuurrentUserId));
			pubgMatchSettlement.setResultSubmitId(pubgUserSubmit.getRowId());
			pubgMatchSettlement.setResultSubmitAccount(pubgUserSubmit.getUserAccount());
			pubgMatchSettlement.setResultSubmitTime(DateUtil.getCurrentDateTime());
			// 来源
			pubgMatchSettlement.setInviteFrom(pubgUserMatch.getInviteFrom());
			
			// USER_STATE
			pubgMatchSettlement.setUserState(pubgUserMatch.getUserState());

			PubgMatchSettlement existPubgMatchSettlement = this.pubgMatchSettlementService.find(query);
			if (StringUtil.isEmpty(existPubgMatchSettlement)) {
				boolean rs = this.pubgUserMatchService.saveMatchTResult(pubgUserMatch, pubgMatchSettlement, pubgMatch);
				if (rs) {
					result.setCode(0);
					result.setMessage("确认名次成功！");
				}
			}else {// 编辑
				pubgMatchSettlement.setRowId(existPubgMatchSettlement.getRowId());
				boolean rs = this.pubgUserMatchService.updateMatchTResult(pubgUserMatch, pubgMatchSettlement, pubgMatch);
				if (rs) {
					result.setCode(0);
					result.setMessage("修改名次成功！");
				}
			}
		}catch (Exception e){
			log.error("确认名次失败", e);
		}
		return result;
	}


}
